package com.sz.mes.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sz.mes.entity.Goods;
import com.sz.mes.entity.TableHead;
import com.sz.mes.entity.warehouse.LatticeGoods;
import com.sz.mes.mapper.GoodsMapper;
import com.sz.mes.mapper.MaterialMapper;
import com.sz.mes.mapper.TableHeadMapper;
import com.sz.mes.mapper.warehouse.LatticeGoodsMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.diboot.core.vo.*;
import com.diboot.iam.annotation.OperationCons;
import com.diboot.iam.annotation.BindPermission;
import com.diboot.iam.annotation.Log;
import com.sz.mes.entity.Material;
import com.sz.mes.dto.MaterialDTO;
import com.sz.mes.vo.MaterialListVO;
import com.sz.mes.vo.MaterialDetailVO;
import com.sz.mes.service.MaterialService;
import lombok.extern.slf4j.Slf4j;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 物料 相关Controller
 *
 * @author hem
 * @version 1.0
 * @date 2023-05-19
 * Copyright © szhs
 */
@RestController
@RequestMapping("/material")
@BindPermission(name = "物料")
@Slf4j
public class MaterialController extends BaseCustomCrudRestController<Material> {

    @Autowired
    private MaterialService materialService;

    @Autowired
    private MaterialMapper materialMapper;

    @Autowired
    private TableHeadMapper tableHeadMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private LatticeGoodsMapper latticeGoodsMapper;

    /**
     * 查询ViewObject的分页数据
     * <p>
     * url请求参数示例: /list?field=abc&pageIndex=1&orderBy=abc:DESC
     * </p>
     *
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_LIST)
//    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping("/list")
    public JsonResult getViewObjectListMapping(MaterialDTO queryDto, Pagination pagination) throws Exception {
        QueryWrapper<Material> materialQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(queryDto.getMaterialName())) {
            materialQueryWrapper.like("material_name", queryDto.getMaterialName());
        } else if (!StringUtils.isEmpty(queryDto.getMaterialNum())) {
            materialQueryWrapper.like("material_num", queryDto.getMaterialNum());
        } else {
            return super.getViewObjectList(queryDto, pagination, MaterialListVO.class);
        }
        return super.getEntityListWithPaging(materialQueryWrapper, pagination);
    }


    /**
     * 根据资源id查询ViewObject
     *
     * @param id ID
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
//    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{id}")
    public JsonResult getViewObjectMapping(@PathVariable("id") Long id) throws Exception {
        return super.getViewObject(id, MaterialDetailVO.class);
    }

    /**
     * 创建资源对象
     *
     * @param entity
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
//    @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/")
    public JsonResult createEntityMapping(@Valid @RequestBody Material entity) throws Exception {
        QueryWrapper<Material> qw = new QueryWrapper<>();
        qw.eq("material_num", entity.getMaterialNum());
        qw.eq("is_deleted", 0);
        Material selectOne = materialMapper.selectOne(qw);
        if (selectOne == null) {
            Goods goods = new Goods();
            goods.setGoodsCode(entity.getMaterialNum());
            goods.setSpecifications(entity.getSpecifications());
            goods.setGoodsName(entity.getMaterialName());
            goodsMapper.insert(goods);
            return super.createEntity(entity);
        } else {
            return JsonResult.FAIL_OPERATION("物料已存在");
        }
    }

    /**
     * 根据ID更新资源对象
     *
     * @param entity
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
//    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PutMapping("/{id}")
    public JsonResult updateEntityMapping(@PathVariable("id") Long id, @Valid @RequestBody Material entity) throws Exception {
        QueryWrapper<Material> qw = new QueryWrapper<>();
        qw.eq("material_num", entity.getMaterialNum());
        qw.eq("is_deleted", 0);
        Material material = materialMapper.selectOne(qw);
        Material currentMaterial = materialMapper.selectById(id);
        if (entity.getMaterialNum().equals(currentMaterial.getMaterialNum())) {
            return super.updateEntity(id, entity);
        } else {
            if (material != null) {
                return JsonResult.FAIL_EXCEPTION("物料已存在");
            } else {
                return super.updateEntity(id, entity);
            }
        }
    }

    /**
     * 根据id删除资源对象
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DELETE)
//    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @DeleteMapping("/{id}")
    public JsonResult deleteEntityMapping(@PathVariable("id") Long id) throws Exception {
        return super.deleteEntity(id);

    }

    /**
     * 根据idList批量删除资源对象
     *
     * @param idList
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_BATCH_DELETE)
//    @BindPermission(name = OperationCons.LABEL_BATCH_DELETE, code = OperationCons.CODE_WRITE)
    @PostMapping("/batchDelete")
    public JsonResult batchDelete(@RequestBody List<Long> idList) throws Exception {
        return super.batchDeleteEntities(idList);
    }

    /**
     * excel导入
     *
     * @param entity
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
//    @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/excel")
    public JsonResult insert(@Valid @RequestBody Material entity) throws Exception {
        List<String> materialNumList = new ArrayList<>();
        String excelData = entity.getExcelData();
        JSONArray objects = JSONObject.parseArray(excelData);
        for (Object object : objects) {
            HashMap<String, String> map = JSONObject.parseObject(JSONObject.toJSONString(object), HashMap.class);
            String materialNum = map.get("料号");
            materialNumList.add(materialNum);
        }

        QueryWrapper<Material> queryWrapper = new QueryWrapper<>();

        for (String materialNum : materialNumList) {
            queryWrapper.eq("material_num", materialNum);
            Material material = materialMapper.selectOne(queryWrapper);
            if (material != null) {
                if (materialNum.equals(material.getMaterialNum())) {
                    return JsonResult.FAIL_OPERATION("物料已存在,导入失败");
                }
            } else {
                return materialService.insert(entity);
            }
        }
        return JsonResult.OK();
    }
}
